<script lang="ts" setup>
import { fetchAllProjectApi, getCommonProjectTagsApi } from '@/api/innovationSquare/projectApi';
import { Pagination, message } from 'ant-design-vue';
import { onMounted, ref, watchEffect } from 'vue';
import type { Project } from '../types/Project';
import axios from 'axios';
import router from '@/router';
import DachuangMarket from './DachuangProjectMarket.vue';
import type { Tag } from '../types/Tag';
import NormalHeader from '@/components/NormalHeader.vue';

// 过滤选项
const filterOptions = ref([
  { key: 'all', label: '竞赛项目迭代创新学生创业项目', value: 1 },
  { key: 'industry', label: '产业需求牵引创新企业接绑项目', value: 2 },
  { key: 'tech', label: '前沿技术探索创新科技攻关项目', value: 3 },
  { key: 'exhibition', label: '北邮第九届研创展', value: 4 },
])
// 项目类别标签
const categories = ref<Tag[]>([]);
// 项目列表
const projects = ref<Project[]>([]);
// 排序方式
const sort = ref(localStorage.getItem('sort') || 'createdTime');
// 当前过滤器
const filter = ref(localStorage.getItem('filter') || 'all');
// 搜索关键字
const search = ref(localStorage.getItem('search') || '');
// 加载状态
const loading = ref(false);
// 当前页码
const currentPage = ref(parseInt(localStorage.getItem('currentPage') || '1'));
// 总页数
const totalPages = ref<number>();
// 项目默认展示类型
const projectStyle = ref<number>(1); // 默认 projectStyle 为 1
// 总项目数
const totalProjects = ref<number>();
// 面包屑导航
const titleParts = '双创广场 > 项目展示'.split(' > ');
// 项目标签列表
const tags = ref<string[]>([])
// 展览标签常量
const EXHIBITION_TAGS: Tag[] = [
  { tagId: "1", name: '智能交叉', tagType: '', selected: false },
  { tagId: "2", name: '基础硬件', tagType: '', selected: false },
  { tagId: "3", name: '人工智能', tagType: '', selected: false },
  { tagId: "4", name: '网络通信', tagType: '', selected: false },
  { tagId: "5", name: '网络安全', tagType: '', selected: false },
];
// 获取项目列表
const fetchProjects = async (reset = false) => {
  loading.value = true;

  try {
    const params: any = {
      sentence: search.value || undefined,
      tags: tags.value,
      sortBy: sort.value,
      pageNum: reset ? 1 : currentPage.value,
      pageSize: 10,
      projectStyle: projectStyle.value,
    };

    const res = await fetchAllProjectApi(params);

    if (res) {
      projects.value = reset ? res.records : [...res.records];
      totalPages.value = res.pages;
      totalProjects.value = res.total;
    }

    if (projectStyle.value === 4) {
      categories.value = EXHIBITION_TAGS;
    }
    else {
      const resTags = await getCommonProjectTagsApi();
      if (resTags)
        categories.value = reset ? resTags.tag : [...resTags.tag];
    }

    // const resTags = await getCommonProjectTagsApi();
    // if (resTags)
    //   categories.value = reset ? resTags.tag : [...resTags.tag];
  }
  catch (error) {
    if (axios.isAxiosError(error)) {
      console.error('Error fetching projects:', error.message);
      message.error(`Error fetching projects: ${error.message}`);
    }
    else if (error instanceof Error) {
      console.error('Unexpected error:', error.message);
      message.error(`Unexpected error: ${error.message}`);
    }
    else {
      console.error('Unknown error:', error);
      message.error('An unknown error occurred');
    }
  }
  finally {
    loading.value = false;
  }
};

// 组件挂载时获取项目列表
onMounted(() => {
  fetchProjects(true);
});

// 监听 currentPage 变化，重新获取项目列表
watchEffect(() => {
  if (currentPage.value > 1)
    fetchProjects();
});

// 监听过滤器变化，重新获取项目列表
const handleFilterChange = (key: string) => {
  const selectedFilterOption = filterOptions.value.find(option => option.key === key);

  if (selectedFilterOption) {
    filter.value = key;
    projectStyle.value = selectedFilterOption.value;
    currentPage.value = 1;
    localStorage.setItem('filter', key);
    // console.log('filter');
    fetchProjects(true); // 过滤后重置项目
  }
};

// 处理标签变化
const handleTagChange = async (key: string) => {
  const selectedTags = categories.value.find(tag => tag.name === key);
  if (selectedTags) {
    const tagIndex = tags.value.indexOf(key);
    if (tagIndex === -1) {
      // 如果标签不在 tags 中，添加它
      tags.value[0] = selectedTags.name
    }
    else {
      // 如果标签已经在 tags 中，移除它
      tags.value = []
    }
    currentPage.value = 1;
    fetchProjects(true);
  }
};

// 处理搜索
const handleSearch = (value: string) => {
  if (value !== search.value) {
    search.value = value;
    currentPage.value = 1;
    localStorage.setItem('search', value);
    // console.log('search');
    fetchProjects(true);
  }
};

// 处理页码变化
const handlePageChange = (pageNumber: number) => {
  currentPage.value = pageNumber;
  localStorage.setItem('currentPage', pageNumber.toString());
  // console.log('换页');
  fetchProjects(true);
};

// 加载更多项目
const loadMoreProjects = () => {
  currentPage.value += 1;
};

// 处理面包屑导航点击
const handleBreadcrumbClick = (part: string) => {
  if (part === '双创广场')
    router.push('/user/dachuang');
}
</script>

<template>
  <a-layout style="display: flex; flex-direction: column; overflow-y: auto;">
    <NormalHeader title="项目展示" />
    <a-input-search v-model="search" placeholder="搜索项目" style="padding: 0.5rem; max-width: 100%;" @search="handleSearch" />

    <a-flex wrap="wrap" style="padding: 0.5rem; padding-top: 0rem;">
      <a-Button
        v-for="(option, index) in filterOptions"
        :key="index"
        :type="option.value === projectStyle ? 'primary' : 'default'"
        style="margin-top: 0.2rem; font-size: 0.75rem; padding: 0.2rem; margin-right: 0.2rem; font-weight: bold;"
        @click="handleFilterChange(option.key)"
      >
        {{ option.label }}
      </a-Button>
    </a-flex>

    <a-flex wrap="wrap" style="padding: 0.5rem; padding-top: 0rem;">
      <a-Button
        v-for="tag in categories"
        :key="tag.tagId"
        :type="tag.name === tags[0] ? 'primary' : 'default'"
        style="margin-top: 0.2rem; font-size: 0.6rem; margin-right: 0.2rem; max-height: 1.5rem; padding: 0.2rem;"
        @click="handleTagChange(tag.name)"
      >
        {{ tag.name }}
      </a-Button>
    </a-flex>

    <div style="display: flex; padding: 0.5rem; overflow-y: auto;">
      <div v-if="projects.length > 0">
        <DachuangMarket
          :projects="projects"
          @load-more-projects="loadMoreProjects"
        />
      </div>

      <p v-else style="text-align: center;">
        暂无数据
      </p>
    </div>

    <div style="display: flex; justify-content: center; white-space: nowrap; max-width: 100%; padding: 0.5rem;">
      <Pagination
        v-model:current="currentPage"
        :total="totalProjects"
        :page-size="10"
        show-quick-jumper
        :show-total="(total: number) => `总共 ${total} 项`" class="pagination" @change="handlePageChange"
      />
    </div>
  </a-layout>
</template>

<style scoped lang="scss">
</style>
